/*
 * Copyright 2007-2008 Andrew O'Malley
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package ws.quokka.plugin.jarbundle;

import org.apache.tools.ant.taskdefs.Jar;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.types.resources.FileResource;

import ws.quokka.core.metadata.Metadata;
import ws.quokka.core.metadata.MetadataAware;
import ws.quokka.core.plugin_spi.support.Setter;
import ws.quokka.core.repo_spi.RepoArtifactId;

import ws.quokka.plugin.lifecycle.LifeCycleImpl;

import java.io.File;

import java.util.Iterator;


/**
 *
 */
public class JarBundlePlugin extends LifeCycleImpl implements MetadataAware {
    //~ Instance fields ------------------------------------------------------------------------------------------------

    private Metadata metadata;

    //~ Methods --------------------------------------------------------------------------------------------------------

    public void setMetadata(Metadata metadata) {
        this.metadata = metadata;
    }

    // TODO: Add support for manifests (possibly merging them)
    public void packageIt() {
        String artifactName = properties().getString("artifactName");
        assertTrue(artifactName.indexOf(",") == -1,
            "Multiple artifacts of type 'jar' have been defined: '" + artifactName
            + "'. Define a separate target for each artifact to bundle");

        RepoArtifactId id = metadata.getArtifactId(artifactName, "jar");
        Path path = getResources().getProjectPath(properties().getString("path"));

        // Create a jar containing all files in the path
        utils().mkdir(getLifeCycle().getPackageOutput());

        Jar jar = (Jar)getProject().createTask("jar");
        jar.setDestFile(getPackageFile(id));

        // Get local resources
        ResourceCollection resources = properties().getResourceCollection("localClasses", null);

        if (resources != null) {
            jar.add(resources);
        }

        for (Iterator i = path.iterator(); i.hasNext();) {
            File file = ((FileResource)i.next()).getFile();
            FileSet fileSet;

            if (file.isDirectory()) {
                fileSet = (FileSet)getProject().createDataType("fileset");
                fileSet.setDir(file);
            } else {
                fileSet = (ZipFileSet)getProject().createDataType("zipfileset");
                ((ZipFileSet)fileSet).setSrc(file);
            }

            jar.addFileset(fileSet);
        }

        Setter setter = new Setter(properties());
        setter.set(jar,
            new String[] {
                "compress", "keepCompression", "encoding", "filesOnly", "defaultExcludes", "manifest", "filesetManifest",
                "update", "whenManifestOnly", "duplicate", "index", "manifestEncoding", "roundUp", "level"
            });

        Path indexJars = properties().getPath("indexJars", null);

        if (indexJars != null) {
            jar.addConfiguredIndexJars(indexJars);
        }

        jar.perform();
    }

    private File getPackageFile(RepoArtifactId id) {
        return new File(getLifeCycle().getPackageOutput(),
            id.toPathString() + "." + metadata.getType(id.getType()).getExtension());
    }
}
